package com.yequan.leetcode.tree.treedfs;

import com.yequan.leetcode.tree.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author : Administrator
 * @date : 2020/4/4
 */
public class TreeDfs {

    /**
     * 使用栈实现dfs
     *
     * @param root
     * @return
     */
    public List<Integer> dfs1(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            res.add(node.val);
            //先入栈右子树
            if (null != node.right) {
                stack.push(node.right);
            }
            if (null != node.left) {
                stack.push(node.left);
            }
        }
        return res;
    }

    /**
     * 递归实现dfs
     *
     * @param root
     * @param res
     */
    public void dfs2(TreeNode root, List<Integer> res) {
        if (null != root) {
            res.add(root.val);
            dfs2(root.left, res);
            dfs2(root.right, res);
        }
    }

}
